How to convert an int to a character array when you don't have access to the C++ Standard Library?

Ok, so I have a great way to convert and int (or any other type) to a string using the stringstream from the standard library. This is listed here:
How to convert an int to a string in C++? (Also doubles, floats, etc…)

However, what do you do if you don’t have access to the C++ Standard Library? There is not stringstream or string so the solution in the above linked-to post won’t work.

So I have created a simple class Int.h that can do this conversion without the C++ Standard Library. Notice it is Int.h with a capital “I”.

It handles both positive and negative numbers.

Int.h

#pragma once

class Int
{
public:
	// Constructor
	Int(int inInt);

	// Desctructor
	~Int();

	// Public functions
	void intToCharArray(char inChar[]);
	char * intToCharArrayPointer();

private:
	// Members
	int mInteger;

	// Functions
	char digitToChar(int inInt);
};

Int.cpp

#include "Int.h"

Int::Int(int inInt)
{
	mInteger = inInt;
}

Int::~Int()
{
}


char Int::digitToChar(int inInt)
{
	char digit[11] = {'0','1','2','3','4','5','6','7','8','9'};
	//digit[0] = '';
	for (short i = 0; i < 10; i++)
	{
		if (inInt == i)
		{
			return digit&#91;i&#93;;
		}
	}
	return '';
}


void Int::intToCharArray(char inChar&#91;&#93;)
{
	char tmpVal&#91;11&#93;;
	int tmpInt = mInteger;
	bool isNegative = false;

	if (mInteger < 0)
	{
		tmpInt *= -1;
		isNegative = true;
	}

	short i = 0;
	while (tmpInt > 0)
	{
		int rightDigit = tmpInt % 10;
		tmpVal[i] = digitToChar(rightDigit);
		tmpInt = tmpInt/10;
		i++;
	}
	tmpVal[i--] = '';
	// tmpVal should now be the number in reverse.

	short j = 0;
	if (isNegative)
	{
		inChar[j++] = '-';
	}
	while (i > -1)
	{
		inChar[j++] = tmpVal[i--];
	}
	inChar[j] = '';
	// inChar should now be the number in correct order.
}

char * Int::intToCharArrayPointer()
{
	// Integers hold as many as 10 character, plus 1 for the null char.
	char * retVal = new char[11];
	intToCharArray(retVal);
	return retVal;
}

Here is a quick example of how to use it. Load this up in your favorite IDE/debugger.

Main.cpp

#include "Int.h"

int main()
{
	Int int1 = 1027;
	Int int2 = -2387809;

	char * charPtr = int1.intToCharArrayPointer();
	char charBuff[11];
	int2.intToCharArray(charBuff);
}

I haven’t seen it fail to convert any integers, positive or negative yet. Let me know if you see anything I could improve on.

Leave a Reply

How to post code in comments?